package com.ai.dao;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.ai.util.SqlLiteHelper;
import com.ai.util.User;

public class DaoUser {
	private SQLiteDatabase db;
	private SqlLiteHelper dbHelper;
	private static final String SCRIPT_DB_DELETE = "DROP TABLE IF EXISTS user";
	private static final String SCRIPT_DB_CREATE = "create table user (_id integer primary "
			+ "key autoincrement, nome text not null, "
			+ "token text not null, email text not null);";

	public DaoUser(Context ctx) {
		dbHelper = new SqlLiteHelper(ctx, "curso", 1, SCRIPT_DB_CREATE,
				SCRIPT_DB_DELETE);
	}

	public long inserir(User c) {
		ContentValues cv = new ContentValues();
		cv.put("nome", c.getNome());
		cv.put("token", c.getToken());
		cv.put("email", c.getEmail());
		db = dbHelper.getWritableDatabase();
		long id = db.insert("user", null, cv);
		db.close();
		return id;
	}

	public long atualizar(User c) {
		ContentValues cv = new ContentValues();
		cv.put("nome", c.getNome());
		cv.put("token", c.getToken());
		cv.put("email", c.getEmail());

		db = dbHelper.getWritableDatabase();
		long rows = db.update("user", cv, "_id = ?",
				new String[] { String.valueOf(c.getId()) });
		db.close();
		return rows; // qtde. de linhas afetadas
	}

	public int excluir(int id) {
		db = dbHelper.getWritableDatabase();
		int rows = db.delete("user", "_id = ?",
				new String[] { String.valueOf(id) });
		return rows; // qtde. de linhas afetadas
	}

	public List<User> buscarCarroPorNome(String nome) {
		List<User> lista = new ArrayList<User>();

		String[] columns = new String[] { "_id", "nome", "token", "email" };
		String[] args = new String[] { nome + "%" };

		db = dbHelper.getWritableDatabase();
		Cursor c = db.query("user", columns, "nome like ?", args, null, null,
				"nome");

		c.moveToFirst();
		while (!c.isAfterLast()) {
			User user = fillUser(c);
			lista.add(user);
			c.moveToNext();
		}
		c.close();
		db.close();
		return lista;
	}

	public List<User> listarUser() {
		List<User> lista = new ArrayList<User>();

		String[] columns = new String[] { "_id", "nome", "token", "email" };

		db = dbHelper.getWritableDatabase();
		Cursor c = db.query("user", columns, "", null, null, null, "nome");

		c.moveToFirst();
		while (!c.isAfterLast()) {
			User user = fillUser(c);
			lista.add(user);
			c.moveToNext();
		}
		c.close();
		db.close();
		return lista;
	}

	private User fillUser(Cursor c) {
		User user = new User();
		user.setId((int) c.getLong(0));
		user.setEmail(c.getString(3));
		user.setNome(c.getString(1));
		user.setToken(c.getString(2));
		return user;
	}
}
